package middleware

import (
	"context"
	"encoding/json"

	"google.golang.org/grpc"

	"gitee.com/krio/helper/logger"
)

// LogGRPCInfo 记录grpc请求与返回日志
func LogGRPCInfo() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {
		in, _ := json.Marshal(req)
		logger.WithContext(ctx).Infof("_grpc_in_info: %+s", in)
		resp, err := handler(ctx, req)
		if err != nil {
			logger.WithContext(ctx).Errorf("_grpc_out_info: err: %+v", err)
		}
		logger.WithContext(ctx).Infof("_grpc_out_info: %+s", resp)
		return resp, err
	}
}
